package com.tsingeye.viid.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tsingeye.common.config.MinioConfig;
import com.tsingeye.common.core.controller.BaseController;
import com.tsingeye.common.core.page.TableDataInfo;
import com.tsingeye.common.utils.ImageUtils;
import com.tsingeye.common.utils.SnowflakeGenerateIdUtil;
import com.tsingeye.common.utils.file.FileUploadUtils;
import com.tsingeye.common.utils.file.MinioUtil;
import com.tsingeye.viid.domain.*;
import com.tsingeye.viid.service.ViidMotorVehicleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 机动车对象接口
 *
 * @author 姜风
 */
@Api(tags = "机动车信息")
@RestController
@Slf4j
public class ViidMotorVehicleController extends BaseController {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private ViidMotorVehicleService viidMotorVehicleService;

    /**
     * 批量新增机动车
     */
    @RequestMapping(value = "/VIID/MotorVehicles", method = RequestMethod.POST)
    public String motorVehicles(@RequestBody String motorVehicleInfo) {
        List<ViidMotorVehicleRequest> insertMotroVehicleList = new ArrayList<>();
        List<SubImageInfo> insertImageList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 返回参数
        JSONObject result = new JSONObject();
        JSONObject ju = new JSONObject();
        // 获取请求的object
        JSONObject jp = JSONObject.parseObject(motorVehicleInfo);
        // 从请求的Object中获取MotorVehicleListObject
        JSONObject motorVehicleListObject = (JSONObject) jp.get("MotorVehicleListObject");
        // 从MotorVehicleListObject中获取MotorVehicleObject
        JSONArray motorVehicleObject = motorVehicleListObject.getJSONArray("MotorVehicleObject");
        String motorVehicleId = null;
        // 遍历机动车列表
        for (Object object : motorVehicleObject) {
            JSONObject jsonObject = (JSONObject) object;
            // 获取机动车
            ViidMotorVehicleRequest viidMotorVehicleRequest = JSONObject.parseObject(jsonObject.toJSONString(), ViidMotorVehicleRequest.class);
            // 设置机动车的id
            viidMotorVehicleRequest.setId(String.valueOf(SnowflakeGenerateIdUtil.getFlowIdInstance().nextId()));
            // 获取机动车的id
            motorVehicleId = viidMotorVehicleRequest.getMotorVehicleId();
            // 判断机动车中的创建时间
            if (ObjectUtil.isEmpty(viidMotorVehicleRequest.getCreateTime())) {
                viidMotorVehicleRequest.setCreateTime(new Timestamp(System.currentTimeMillis()));
            }
            // 获取图片信息
            SubImageInfoObject subImageList = viidMotorVehicleRequest.getSubImageList();
            // 判断机动车对象中的列表是否为空
            if (ObjectUtil.isNotEmpty(subImageList) && CollUtil.isNotEmpty(subImageList.getSubImageInfoObject())) {
                // 遍历每个图片对象
                for (SubImage subImage : subImageList.getSubImageInfoObject()) {
                    // 新建SubImageInfo
                    SubImageInfo subImageInfo = new SubImageInfo();
                    // base64转换成MultipartFIle
                    MultipartFile file = ImageUtils.base64ToMultipartFile(subImage.getData());
                    // 上传minIO
                    String url = uploadFileMinio(file, subImage.getFileFormat());
                    // 设置主键
                    subImage.setId(String.valueOf(SnowflakeGenerateIdUtil.getFlowIdInstance().nextId()));
                    subImage.setViidId(viidMotorVehicleRequest.getId());
                    // 设置机动车Id
                    subImage.setMotorVehicleId(viidMotorVehicleRequest.getMotorVehicleId());
                    // 设置base64的字节数组
//                    subImage.setDataBytes(subImage.getData().getBytes(StandardCharsets.UTF_8));
                    // 设置minio的url
                    subImage.setImageUrl(url);
                    // 设置创建时间
                    subImage.setCreateTime(sdf.format(new Date()));
                    // 转换
                    convertImages(subImageInfo, subImage);
                    // 添加到照片列表中
                    insertImageList.add(subImageInfo);
                }
            }

            // 添加到机动车列表
            insertMotroVehicleList.add(viidMotorVehicleRequest);
        }
        // 批量新增机动车及机动车照片列表
        if (CollUtil.isNotEmpty(insertMotroVehicleList) && CollUtil.isNotEmpty(insertImageList)) {
            int insert = viidMotorVehicleService.batchInsertMotorVehiclesAndMotorVehiclesImages(insertMotroVehicleList, insertImageList);
        }
        ju.put("Id", motorVehicleId);
        ju.put("StatusCode", 0);
        ju.put("RequestURL", "/VIID/MotorVehicles");
        ju.put("StatusString", "OK");
        result.put("ResponseStatusObject", ju);
        log.info("打印返回的请求参数：{}", result.toJSONString());

        return result.toJSONString();
    }

    private void convertImages(SubImageInfo subImageInfo, SubImage subImage) {
        subImageInfo.setId(subImage.getId());
        subImageInfo.setImageUrl(subImage.getImageUrl());
        subImageInfo.setMotorVehicleId(subImage.getMotorVehicleId());
        subImageInfo.setEventSort(subImage.getEventSort());
        subImageInfo.setDeviceId(subImage.getDeviceID());
        subImageInfo.setStoragePath(subImage.getStoragePath());
        subImageInfo.setType(subImage.getType());
        subImageInfo.setFileFormat(subImage.getFileFormat());
        subImageInfo.setShotTime(subImage.getShotTime());
        subImageInfo.setWidth(subImage.getWidth());
        subImageInfo.setHeight(subImage.getHeight());
//        subImageInfo.setDataBytes(subImage.getDataBytes());
        subImageInfo.setCreateTime(subImage.getCreateTime());
        subImageInfo.setViidId(subImage.getViidId());
    }

    /**
     * minio图片上传
     *
     * @param file file
     * @return 地址
     */
    public String uploadFileMinio(MultipartFile file, String fileFormat) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不存在！");
        }
        // 判断存储桶是否存在
        if (!minioUtil.bucketExists(minioConfig.getBucketName())) {
            minioUtil.makeBucket(minioConfig.getBucketName());
        }
        if ("Jpeg".equals(fileFormat)) {
            fileFormat = "jpg";
        }
        // 生成文件名
        String fineName = FileUploadUtils.extractFilename(file) + "." + fileFormat;
        try {
            // 上传文件
            Boolean upload = minioUtil.upload(file, fineName, minioConfig.getBucketName());
            // 判断上传是否成功
            if (!upload) {
                return null;
            }
        } catch (Exception e) {
            return null;
        }

        return "/" + minioConfig.getBucketName() + "/" + fineName;
    }

    /**
     * 查询机动车信息列表
     */
    @ApiOperation(value = "机动车照片分页查询", notes = "分页查询")
    @PreAuthorize("@ss.hasPermi('viid:motorvehicle:list')")
    @GetMapping("/viid/motorvehicle/list")
    public TableDataInfo list(ViidMotorVehicle viidMotorVehicle) {
        startPage();
        List<ViidMotorVehicle> list = viidMotorVehicleService.selectViidMotorVehicleList(viidMotorVehicle);
        return getDataTable(list);
    }
}
